<template>
  <view id="kaochang-moni-container-wrap">
    <navbar :title="title" mode="kaochang-navbar"></navbar>
    <view
      :style="{width:containerStyle.width, height:containerStyle.height, transform:containerStyle.transform,'transform-origin':containerStyle['transform-origin'] }"
      v-if="inited" class="kaochang-moni-container">
      <view class="flex timu-all-container">
        <view class="flex f1">
          <view class="flex v" style="width: 200rpx">
            <view class="group-container kaoshi">
              <view class="label">理论考试</view>
              <view class="text">第01考台</view>
            </view>
            <view class="group-container user">
              <view class="label">考生信息</view>
              <view class="avatar-container">
                <image
                  :src="(mine && mine.avatarUrl )? mine.avatarUrl : 'http://down.qwdata.vip/app_icon/1672758529606'"
                  mode="aspectFill" class="avatar"></image>
              </view>
              <view class="row">
                <view class="key">姓名：</view>
                <view class="value">{{ (mine && mine.name) || '游客' }}</view>
              </view>
              <view class="row">
                <view class="key">类别：</view>
                <view class="content" v-if="mine.carType === 1">小车</view>
                <view class="content" v-else-if="mine.carType === 2">货车</view>
                <view class="content" v-else-if="mine.carType === 3">客车</view>
              </view>
              <view class="row">
                <view class="key">科目：</view>
                科目{{ kemu == 1 ? '一' : '四' }}
              </view>
            </view>
            <view class="group-container time">
              <view class="label">剩余时间</view>
              <view class="text">{{ timeFormat(max - time) }}</view>
            </view>
          </view>
          <view class="flex v f1">
            <view class="group-container timu" @touchmove="onMove" @touchstart="onStart">
              <view class="label">考试题目</view>
              <view style="height: 100%;overflow: hidden">
                <view v-if="question" :style="{transform: 'translateY('+ x +'px)'}">
                  <view class="title">{{ question.title }}</view>
                  <view v-if="question.type!=3">
                    <view class="option">A.{{ question.option1 }}</view>
                    <view class="option">B.{{
                        question.option2
                      }}
                    </view>
                    <view class="option" v-if="question.option3">C.{{
                        question.option3
                      }}
                    </view>
                    <view class="option" v-if="question.option4">D.{{
                        question.option4
                      }}
                    </view>
                  </view>
                </view>
              </view>
            </view>
            <view class="flex answer-container" v-if="question">
              <view class="tips">
                您选择的答案：
                <view v-if="question.type ===3 && selected">
                  {{ selected === 'A' ? '√' : '×' }}
                </view>
                <view v-else>{{ selected }}</view>
              </view>
              选项：
              <view v-if="question.type!=3" class="flex">
                <view :class="['btn', activeOption('A')]" @click="selectOption('A')">A</view>
                <view :class="['btn', activeOption('B')]" @click="selectOption('B')">B</view>
                <view :class="['btn', activeOption('C')]" v-if="question.option3" @click="selectOption('C')">C</view>
                <view :class="['btn', activeOption('D')]" v-if="question.option4" @click="selectOption('D')">D</view>
              </view>
              <view v-else class="flex">
                <view :class="['btn', activeOption('A')]" @click="selectOption('A')">√</view>
                <view :class="['btn', activeOption('B')]" @click="selectOption('B')">×</view>
              </view>
            </view>
          </view>
        </view>
        <view class="flex v" style="margin-top: 20rpx">
          <view class="timu-container bg left">题目</view>
          <view class="timu-container bg left" v-for="(n, i) in 10" :key="n">{{ i + 1 }}行</view>
        </view>
        <view class="flex v" style="margin-top: 20rpx">
          <view class="flex">
            <view class="timu-container bg" v-for="(n, i) in kemu == 1?10: 5" :key="n">{{ i + 1 }}列</view>
          </view>
          <view :class="['timus-container', 'kemu'+kemu]">
            <view class="timu-container" v-for="(item, i) in list" :key="item.id" @click="select(i)">
              <view v-if="!item.answer" :class="[currentIndex===i?'status1':'status0']">{{ i + 1 }}</view>
              <view v-else-if="item.answer.status" class="status0">
                <view v-if="item.question.type !== 3">{{ item.answer.result }}</view>
                <view v-else>{{ item.answer.result === 'A' ? '√' : '×' }}</view>
              </view>
              <view v-else class="status2">
                <view v-if="item.question.type !== 3">{{ item.answer.result }}</view>
                <view v-else>{{ item.answer.result === 'A' ? '√' : '×' }}</view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="flex process-row">
        <view class="tips" v-if="question">
          <view class="tips1">操作提示：{{ question.typeStr }}</view>
          <view class="tips2">请在备选答案中选择你认为正确的答案！</view>
        </view>
        <view :class="['btn', isFirst? '': 'white']" @click="prevQuestion()">上一题</view>
        <view :class="['btn', isEnd? '': 'white']" @click="nextQuestion()">下一题</view>
        <view class="btn white" @click="trySubmit">交卷</view>
      </view>
      <view class="pic-row">
        <image :src="img" v-if="img" mode="aspectFit"
               @click="toPreview([img], img)"
               style="height: 250rpx"></image>
      </view>
      <SubmitDialog title="错题学习" v-if="showError" :selected="selected" :question="question" showDownTime="close"
                    @close="closeErrorDialog">
        <template v-slot>
          <view class="dialog-tips">
            {{ question.title }}
          </view>
          <view v-if="question.type!=3">
            <view class="dialog-tips">A.{{ question.option1 }}</view>
            <view class="dialog-tips">B.{{ question.option2 }}</view>
            <view class="dialog-tips" v-if="question.option3">C.{{ question.option3 }}</view>
            <view class="dialog-tips" v-if="question.option4">D.{{ question.option4 }}</view>
          </view>
        </template>
      </SubmitDialog>
      <SubmitDialog title="考试确认" v-if="showConfirm">
        <template v-slot>
          <view class="dialog-tips">操作提示：</view>
          <view class="dialog-tips">
            您当前考试答对{{ zhengqueCount }}题，答错{{ cuowuCount }}题，未答{{
              list.length - zhengqueCount - cuowuCount
            }}题
          </view>
          <view class="dialog-tips">1.点击【确认交卷 】，将提交考试成绩，考试结束！</view>
          <view class="dialog-tips">2.点击【继续考试 】，将关闭本窗口，继续考试！</view>
        </template>
        <template v-slot:footer>
          <view class="flex h vc hc">
            <view class="dialog-btn" @click="showResultDialog">
              确认交卷
            </view>
            <view class="dialog-btn" @click="continueKaoshi">
              继续考试
            </view>
          </view>
        </template>
      </SubmitDialog>
      <SubmitDialog title="信息提示" v-if="showResult" showDownTime="exit" @exit="toExit">
        <template v-slot>
          <view class="dialog-tips">姓名：{{ (mine && mine.name) || '游客' }}</view>
          <view class="dialog-tips" v-if="result.status">您本次模拟考试得分{{ result.score }}分，恭喜考试及格！</view>
          <view class="dialog-tips" v-if="!result.status">您本次模拟考试得分{{ result.score || 0 }}分，不及格！</view>
          <view class="dialog-tips" v-if="!result.status">祝您下次考试成功！</view>
        </template>
        <template v-slot:footer>
          <view class="flex h vc hc">
            <view class="dialog-btn" @click="toExit">
              关闭
            </view>
            <view class="dialog-btn" @click="toWrong">
              查看错题
            </view>
          </view>
        </template>
      </SubmitDialog>
      <PreviewDialog ref="PreviewDialog"></PreviewDialog>
      <WXPageBackIntercept ref="mpBack" @back="onMpBack"></WXPageBackIntercept>
    </view>
  </view>
</template>

<script>
import {mapGetters, mapActions} from 'vuex'
import SubmitDialog from "./SubmitDialog.vue";
import PreviewDialog from "./PreviewDialog.vue";
import Navbar from "../../components/navbar.vue";
import WXPageBackIntercept from "@/components/WXPageBackIntercept.vue";

export default {
  components: {WXPageBackIntercept, Navbar, SubmitDialog, PreviewDialog},
  data() {
    return {
      kemu: null,
      title: null,
      type: null,
      currentIndex: 0,
      screenWidth: 0,
      screenHeight: 0,
      x: 0,
      inited: false,
      rotate: true,
      list: [],
      question: null,
      selected: '',
      max: 45 * 60,
      // max: 5,
      time: 0,
      showConfirm: false,
      showResult: false,
      showError: false,
      zhengqueCount: 0,
      cuowuCount: 0,
      result: {}
    }
  },
  computed: {
    ...mapGetters(['systemInfo', 'mine', 'topBar']),
    isFirst() {
      return this.currentIndex === 0
    },
    isEnd() {
      return this.currentIndex + 1 >= this.list.length
    },
    containerStyle() {
      if (this.rotate) {
        return {
          width: this.screenHeight + 'px',
          height: this.screenWidth + 'px',
          transform: 'rotate(90deg)',
          'transform-origin': this.screenWidth / 2 + 'px'
        }
      }
      return {
        height: this.screenHeight + 'px',
        width: this.screenWidth + 'px',
        transform: '',
        'transform-origin': '',
      }
    },
    img() {
      if (this.question) {
        if (this.question.img) {
          return this.question.img
        }
        if (this.question.signIcon) {
          return this.question.signIcon.img
        }
      }
      return ''
    },
  },
  async onLoad({type = 'kaochang', kemu, title = '真实考场模拟'}) {
    this.type = type
    this.kemu = kemu
    this.title = title
    await this.initQuestions()
    setTimeout(() => {
      this.initInfoRect()
    }, 300)
    this._timeDown = setInterval(() => {
      if (this.time >= this.max) {
        console.log('结束考试')
        this.showResultDialog()
        clearInterval(this._timeDown)
        return
      }

      this.time += 1
    }, 1000)
  },
  destroyed() {
    console.log('destroyed')
    clearInterval(this._timeDown)
  },
  methods: {
    ...mapActions(['answer']),
    ...mapActions('question', ['questionList', 'questionInfo', 'questionAnswer', 'kaoshiSubmit']),
    toWrong() {
      uni.redirectTo({
        url: '/pages/mine_wrong/mine_wrong?kemu=' + this.kemu
      });
    },
    timeFormat(time) {
      let minutes = Math.floor((time) / 60) + ''
      if (minutes.length < 2) {
        minutes = '0' + minutes
      }
      let seconds = (time) % 60 + ''
      if (seconds.length < 2) {
        seconds = '0' + seconds
      }
      return minutes + ':' + seconds
    },
    async trySubmit() {
      await this.submitAnswer()
      this.showConfirm = true
      console.log('trySubmit')
    },
    onMpBack(args) {
      console.log(args, this._forceExitExamTime, Date.now() - this._forceExitExamTime)
      if (this._forceExitExamTime && Date.now() - this._forceExitExamTime < 1000) {
        uni.navigateBack()
        return
      }

      this.$refs.mpBack.setData(true)
      this.showConfirm = true
    },
    continueKaoshi() {
      this.showConfirm = false
    },
    toExit() {
      console.log('toExit')
      this._forceExitExamTime = Date.now()
      uni.navigateBack()
    },
    showResultDialog() {
      const score = this.kemu == 1 ? this.zhengqueCount : this.zhengqueCount * 2
      this.result = {
        score,
        status: score >= 90
      }
      this.showResult = true

      this.kaoshiSubmit({
        type: this.type,
        score,
        status: this.result.status,
        time: this.time,
        kemu: this.kemu,
        zhengque: this.zhengqueCount,
        cuowu: this.cuowuCount,
      })
    },
    activeOption(option) {
      return this.selected.indexOf(option) > -1 ? 'active' : ''
    },
    async initInfoRect() {
      this.$ = uni.createSelectorQuery()
      console.log('initInfoRect', this.topBar)
      const containerRect = await this.queryViewRect('#kaochang-moni-container-wrap')
      this.screenWidth = containerRect.width
      this.screenHeight = containerRect.height
      if (this.topBar.style === 'custom') {
        this.screenHeight -= this.topBar.height
      }

      this.inited = true
    },
    async initQuestions() {
      const res = await this.questionList({type: this.type, kemu: this.kemu})
      const list = []
      res.list.map(item => {
        list.push({
          params: item,
          answer: null
        })
      })
      this.list = list
      this.currentIndex = 0
      await this.initQuestion()
      // this.showResult = true
    },
    selectOption(option) {
      if (this.question.type === 2) {
        const i = this.selected.indexOf(option)
        let arr;
        if (i > -1) {
          arr = this.selected.split('')
          arr.splice(i, 1)
        } else {
          this.selected += option
          arr = this.selected.split('')
        }
        this.selected = arr.sort().join('')
      } else {
        this.selected = option
      }
      console.log(this.question.type, this.selected)
      // this.list[this.currentIndex].answer = {
      //   result,
      //   status: this.question.answerStr === result
      // }
      // setTimeout(() => {
      //   this.nextQuestion()
      // }, 500)
    },
    async initQuestion() {
      uni.showLoading({
        title: '',
        mask: true
      })
      const id = this.list[this.currentIndex].params.id
      const question = await this.questionInfo(id)
      this.selected = ''
      question.title = (1 + this.currentIndex) + '.' + question.title
      this.list[this.currentIndex].question = question
      if (this.list[this.currentIndex].answer) {
        this.selected = this.list[this.currentIndex].answer.result
      }
      this.question = question
      this.x = 0
      uni.hideLoading()
    },
    queryViewRect(selector) {
      return new Promise(resolve => {
        this.$.select(selector).boundingClientRect((res) => {
          resolve(res)
        }).exec()
      })
    },
    toPreview(arr, current) {
      this.$refs.PreviewDialog.show(current)
    },
    prevQuestion() {
      if (this.currentIndex > 0) {
        this.currentIndex--
        this.initQuestion()
      }
    },
    select(i) {
      this.currentIndex = i
      this.initQuestion()
    },
    closeErrorDialog() {
      this.showError = false
      this.requestNextQuestion()
    },
    async nextQuestion() {
      if (await this.submitAnswer()) {
        this.requestNextQuestion()
      }
    },
    async submitAnswer() {
      if (!this.list[this.currentIndex].answer && this.selected) {
        const status = this.question.answerStr === this.selected
        this.list[this.currentIndex].answer = {
          result: this.selected,
          status
        }
        uni.showLoading({
          title: '',
          mask: true
        })
        try {
          await this.questionAnswer({
            type: 'kaochang',
            id: this.question.id,
            result: this.selected,
            status: status ? 1 : -1,
            index: this.index,
            kemu: this.kemu
          })
          this.answer()
        } catch (e) {

        }
        uni.hideLoading()
        if (status) {
          this.zhengqueCount++
        } else {
          this.cuowuCount++
          this.showError = true
          return false
        }
      }

      return true
    },
    onStart(event) {
      // console.log(e)
      // this.x = e.detail.x
      // this.y = e.detail.y

      var touch = event.touches[0] || event.changedTouches[0]
      // console.log(event)
      this.startPageX = touch.pageX
    },
    onMove(event) {
      // console.log(e)
      // this.x = e.detail.x
      // this.y = e.detail.y

      const touch = event.touches[0] || event.changedTouches[0]
      // console.log(event)
      const pageX = touch.pageX
      const d = (this.startPageX - pageX)
      if (this.x + d > 0) {
        this.x = 0
      } else {
        this.x += d
      }
      this.startPageX = pageX
      console.log(this.startPageX - pageX)
    },
    requestNextQuestion() {
      if (this.currentIndex < this.list.length - 1) {
        this.currentIndex++
        uni.showLoading({
          title: '',
          mask: true
        })
        setTimeout(() => {
          this.initQuestion()
        }, 300)
      }
    }
  }
}
</script>

<style lang="scss">
page {
  height: 100%;
}

#kaochang-moni-container-wrap {
  background-color: #f5f1ef;
  height: 100%;

  ::v-deep .kaochang-navbar {
    background-color: #f5f1ef;
  }

  .kaochang-moni-container {
    display: flex;
    flex-direction: column;

    .dialog-tips {
      margin-top: 10rpx;
      font-size: 15px;
      color: #343630;

      &:first-child {
        margin-top: 0;
      }
    }

    .dialog-btn {
      width: 160rpx;
      height: 68rpx;
      background-color: #fff;
      border-radius: 5rpx;
      font-size: 15px;
      color: #000000;
      margin-left: 60rpx;
      margin-top: 36rpx;
      display: flex;
      justify-content: center;
      align-items: center;

      &:first-child {
        margin-left: 0;
      }
    }

    .answer-container {
      margin-top: 8rpx;
      height: 67rpx;
      display: flex;
      align-items: center;
      font-size: 12px;
      color: #535353;
      margin-left: 20rpx;

      .tips {
        color: #0853CD;
        flex: 1;
        display: flex;
        align-items: center;
      }

      .btn {
        width: 62rpx;
        height: 62rpx;
        border: 1px solid #ddd;
        font-size: 15px;
        color: #000;
        display: flex;
        justify-content: center;
        background-color: #fff;
        align-items: center;
        margin-right: 20rpx;

        &:last-child {
          margin-right: 10rpx;
        }

        &.active {
          background-color: #0E57CD;
          color: #fff;
          border: 1px solid #0E57CD;
        }
      }
    }

    .group-container {
      border: 1px solid #cdcdcd;
      position: relative;
      margin-top: 20rpx;

      .text {
        margin-top: 12rpx;
      }

      &.kaoshi {
        height: 50rpx;
        font-size: 10px;
        text-align: center;
      }

      &.time {
        height: 50rpx;
        font-size: 10px;
        text-align: center;
      }

      &.timu {
        margin-left: 10rpx;
        margin-right: 10rpx;
        font-size: 14px;
        color: #30322C;
        line-height: 22px;
        height: 295rpx;
        padding-top: 25rpx;
        box-sizing: border-box;

        .mv {
          transform: rotate(90deg);
        }

        .title {
          margin-left: 30rpx;
          font-size: 16px;
        }

        .option {
          font-size: 16px;
          margin-left: 30rpx;
        }

        .label {
          position: absolute;
          right: auto;
          top: -24rpx;
          padding-left: 20rpx;
          padding-right: 20rpx;
        }
      }

      &.user {
        flex: 1;
        font-size: 10px;
        display: flex;
        flex-direction: column;
        padding-bottom: 10rpx;

        .avatar-container {
          display: flex;
          justify-content: center;
          align-items: center;
        }

        .avatar {
          width: 80rpx;
          height: 80rpx;
          border-radius: 86rpx;
          margin-top: 20rpx;
          margin-bottom: 10rpx;
        }

        .row {
          display: flex;
          margin-left: 20rpx;
          margin-right: 10rpx;

          .key {
            white-space: nowrap;
          }

          .value {
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
          }
        }
      }

      .label {
        position: absolute;
        font-size: 11px;
        color: #0853CD;
        top: -20rpx;
        left: 20rpx;
        text-align: center;
        right: 20rpx;
        background-color: #f5f1ef;
        z-index: 10;
      }
    }

    .timus-container {
      display: flex;
      flex-wrap: wrap;
      margin-right: 10rpx;

      &.kemu1 {
        width: 340rpx;
      }

      &.kemu4 {
        width: 175rpx;
      }
    }

    .timu-container {
      display: flex;

      &.left {
        width: 40rpx;
      }

      &.bg {
        background-color: #5cadef;
        display: flex;
        color: #000;
        justify-content: center;
        align-items: center;
      }

      .status0 {
        flex: 1;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      .status1 {
        flex: 1;
        background-color: #3f9ae6;
        display: flex;
        color: #fff;
        justify-content: center;
        align-items: center;
      }

      .status2 {
        flex: 1;
        display: flex;
        color: #f4433b;
        justify-content: center;
        align-items: center;
      }

      white-space: nowrap;
      width: 32rpx;
      height: 32rpx;
      font-size: 8px;
      background-color: #fff;
      border-right: 1px solid #cdcdcd;
      border-bottom: 1px solid #cdcdcd;
    }

    .timu-all-container {
      height: 390rpx;
      overflow: hidden;
    }

    .pic-row {
      border-left: 1px solid #cdcdcd;
      border-right: 1px solid #cdcdcd;
      border-bottom: 1px solid #cdcdcd;
      margin-right: 10rpx;
      flex: 1;
      display: flex;
      justify-content: center;
      height: 270rpx;
      box-sizing: border-box;
    }

    .process-row {
      margin-top: 10rpx;
      border-top: 2px solid #4673B0;
      border-bottom: 2px solid #4673B0;
      border-left: 1px solid #cdcdcd;
      border-right: 1px solid #cdcdcd;
      padding-left: 20rpx;
      margin-right: 10rpx;
      display: flex;
      align-items: center;
      height: 90rpx;

      .btn {
        width: 148rpx;
        height: 60rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        border: 1px solid #ddd;
        border-radius: 8rpx;
        font-size: 13px;
        color: #30322c;
        margin: 12rpx 16rpx;
        background-color: #e9e9e9;

        &.white {
          background-color: #fff;
        }
      }

      .tips {
        flex: 1;

        .tips1 {
          font-size: 12px;
          color: red;
        }

        .tips2 {
          font-size: 10px;
          color: #30322C;
        }
      }
    }
  }
}
</style>
